<template>
	<div class="awards">
		<div class="page-header">
			<h1 class="page-title">奖项信息管理</h1>
			<p class="page-subtitle">填报您获得的奖项，并上传证书扫描件</p>
		</div>

		<div style="margin-bottom: 20px;">
			<el-button type="success" @click="exportData">
				<el-icon><Download /></el-icon>
				导出数据
			</el-button>
			<el-button type="primary" style="margin-left: 8px;" @click="openCreate()">
				<el-icon><Trophy /></el-icon>
				在线填报
			</el-button>
		</div>

		<el-card>
			<el-table :data="tableData" style="width: 100%">
				<el-table-column prop="achievementName" label="成果/项目名称" min-width="220" show-overflow-tooltip />
				<el-table-column prop="awardName" label="奖项名称" min-width="200" show-overflow-tooltip />
				<el-table-column prop="category" label="奖项类别" width="120" />
				<el-table-column prop="level" label="奖项级别" width="100">
					<template #default="{ row }">
						<el-tag :type="levelTag(row.level)">{{ row.level }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="grade" label="获奖等级" width="100">
					<template #default="{ row }">
						<el-tag type="success">{{ row.grade || '-' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="awardingDate" label="获奖日期" width="120" />
				<el-table-column prop="awardingOrg" label="颁奖单位" min-width="200" show-overflow-tooltip />
				<el-table-column prop="certificateNo" label="证书编号" min-width="160" show-overflow-tooltip />
				<el-table-column prop="status" label="状态" width="110">
					<template #default="{ row }">
						<el-tag :type="statusTag(row.status)">{{ statusText(row.status) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="220" fixed="right">
					<template #default="{ row }">
						<el-button size="small" @click="handleView(row)">查看</el-button>
						<el-button size="small" type="primary" :disabled="!canEdit(row)" @click="handleEdit(row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!-- 新增/编辑对话框 -->
		<el-dialog v-model="showDialog" :title="isEdit ? '编辑奖项' : '在线填报奖项'" width="720px">
			<el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
				<el-form-item label="奖项名称" prop="award_name">
					<el-input v-model="form.award_name" placeholder="如：第十届校级教学成果奖" />
				</el-form-item>

				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="奖项类别" prop="category">
							<el-select v-model="form.category" placeholder="请选择" style="width: 100%" filterable>
								<el-option label="教学成果奖" value="教学成果奖" />
								<el-option label="科技进步奖" value="科技进步奖" />
								<el-option label="社科优秀成果奖" value="社科优秀成果奖" />
								<el-option label="优秀教师" value="优秀教师" />
								<el-option label="先进个人" value="先进个人" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="奖项级别" prop="level">
							<el-select v-model="form.level" placeholder="请选择" style="width: 100%">
								<el-option label="校级" value="校级" />
								<el-option label="省部级" value="省部级" />
								<el-option label="国家级" value="国家级" />
								<el-option label="国际级" value="国际级" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="获奖等级" prop="grade">
							<el-select v-model="form.grade" placeholder="可选" clearable style="width: 100%">
								<el-option label="特等" value="特等" />
								<el-option label="一等" value="一等" />
								<el-option label="二等" value="二等" />
								<el-option label="三等" value="三等" />
								<el-option label="优秀" value="优秀" />
								<el-option label="提名" value="提名" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="颁奖单位" prop="awarding_org">
							<el-input v-model="form.awarding_org" placeholder="如：教务处、省教育厅" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="获奖日期" prop="awarding_date">
							<el-date-picker v-model="form.awarding_date" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" format="YYYY-MM-DD"/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="证书编号" prop="certificate_no">
							<el-input v-model="form.certificate_no" placeholder="可选，用于避免重复" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="成果/项目名称" prop="achievement_name">
					<el-input v-model="form.achievement_name" placeholder="请填写成果/关联的项目名称" />
				</el-form-item>
				<!-- 状态仅管理员可改，staff 编辑不展示 -->
				<el-form-item v-if="isEdit && isAdmin" label="状态" prop="status">
					<el-select v-model="form.status" placeholder="请选择" style="width: 100%">
						<el-option label="待审核" value="PENDING" />
						<el-option label="已通过" value="APPROVED" />
						<el-option label="已驳回" value="REJECTED" />
					</el-select>
				</el-form-item>

				<el-form-item v-if="!isEdit" label="证书扫描件">
					<el-upload
						v-model:file-list="fileList"
						class="upload-demo"
						drag
						:limit="3"
						:before-upload="beforeUpload"
						:auto-upload="false"
						accept=".jpg,.jpeg,.png,.pdf"
					>
						<el-icon class="el-icon--upload"><UploadFilled /></el-icon>
						<div class="el-upload__text">将证书拖到此处，或<em>点击上传</em>（可选）</div>
						<template #tip>
							<div class="el-upload__tip">仅支持 JPG/PNG/PDF，单个不超过 20MB，最多 3 个（附件为可选项）</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showDialog = false">取消</el-button>
				<el-button type="primary" :loading="submitting" @click="handleSubmit">{{ isEdit ? '保存' : '提交' }}</el-button>
			</template>
		</el-dialog>

		<!-- 查看对话框 -->
		<el-dialog v-model="showView" title="查看奖项" width="600px">
			<el-descriptions :column="1" border>
				<el-descriptions-item label="奖项名称">{{ currentRow?.awardName }}</el-descriptions-item>
				<el-descriptions-item label="类别">{{ currentRow?.category }}</el-descriptions-item>
				<el-descriptions-item label="级别">{{ currentRow?.level }}</el-descriptions-item>
				<el-descriptions-item label="获奖等级">{{ currentRow?.grade || '-' }}</el-descriptions-item>
				<el-descriptions-item label="获奖日期">{{ currentRow?.awardingDate }}</el-descriptions-item>
				<el-descriptions-item label="颁奖单位">{{ currentRow?.awardingOrg }}</el-descriptions-item>
				<el-descriptions-item label="状态">{{ statusText(currentRow?.status) }}</el-descriptions-item>
			</el-descriptions>
			<template #footer>
				<el-button @click="showView = false">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Trophy, UploadFilled, Download } from '@element-plus/icons-vue'
import { getMyAwards, createAward, uploadAwardAttachment, updateAward, deleteAward } from '@/api/award'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const isAdmin = userStore.isAdmin

const showDialog = ref(false)
const isEdit = ref(false)
const showView = ref(false)
const currentRow = ref(null)
const formRef = ref()
const submitting = ref(false)

const form = reactive({
	award_name: '',
	achievement_name: '',
	category: '',
	level: '',
	grade: '',
	awarding_org: '',
	awarding_date: '',
	certificate_no: '',
	status: 'PENDING'
})

const rules = {
	award_name: [{ required: true, message: '请输入奖项名称', trigger: 'blur' }],
	category: [{ required: true, message: '请选择奖项类别', trigger: 'change' }],
	level: [{ required: true, message: '请选择奖项级别', trigger: 'change' }],
	awarding_date: [{ required: true, message: '请选择获奖日期', trigger: 'change' }]
}

const fileList = ref([])
const tableData = ref([])

const levelTag = (level) => ({ '校级': 'info', '省部级': 'warning', '国家级': 'danger', '国际级': 'success' }[level] || 'info')
const statusTag = (s) => ({ 'PENDING': 'warning', 'APPROVED': 'success', 'REJECTED': 'danger' }[s] || 'info')
const statusText = (s) => ({ 'PENDING': '待审核', 'APPROVED': '已通过', 'REJECTED': '已驳回' }[s] || s)

const canEdit = (row) => {
	// 管理员不受限制；staff 只能编辑待审核
	return isAdmin || row.status === 'PENDING'
}

const openCreate = () => {
	isEdit.value = false
	Object.assign(form, { award_name: '', achievement_name: '', category: '', level: '', grade: '', awarding_org: '', awarding_date: '', certificate_no: '', status: 'PENDING' })
	fileList.value = []
	showDialog.value = true
}

const beforeUpload = (file) => {
	const okType = ['image/jpeg','image/png','application/pdf']
	const ok = okType.includes(file.type) && file.size <= 20 * 1024 * 1024
	if (!ok) ElMessage.error('请上传 JPG/PNG/PDF 且不超过20MB')
	return ok
}

const loadTable = async () => {
	try {
		const res = await getMyAwards()
		const raw = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
		tableData.value = raw.map(r => ({
			...r,
			achievementName: r.achievementName ?? r.achievement_name,
			awardName: r.awardName ?? r.award_name ?? r.name,
			awardingDate: r.awardingDate ?? r.awarding_date,
			awardingOrg: r.awardingOrg ?? r.awarding_org,
			certificateNo: r.certificateNo ?? r.certificate_no
		}))
	} catch (e) {
		console.error(e)
	}
}

const handleSubmit = async () => {
	try {
		if (!formRef.value) return
		await formRef.value.validate()
		submitting.value = true
		if (!isEdit.value) {
			// 附件不再是必填项，可以不上传
			const res = await createAward({
				award_name: form.award_name,
				achievement_name: form.achievement_name,
				category: form.category,
				level: form.level,
				grade: form.grade || null,
				awarding_org: form.awarding_org,
				awarding_date: form.awarding_date,
				certificate_no: form.certificate_no || null
			})
			const awardId = res?.id || res?.data?.id
			if (!awardId) throw new Error('创建奖项失败')
			// 如果有附件才上传
			if (fileList.value.length > 0) {
				for (const f of fileList.value) {
					await uploadAwardAttachment(awardId, f.raw || f, '证书')
				}
			}
			ElMessage.success('提交成功，等待审核')
		} else {
			const payload = {
				award_name: form.award_name,
				achievement_name: form.achievement_name,
				category: form.category,
				level: form.level,
				grade: form.grade || null,
				awarding_org: form.awarding_org,
				awarding_date: form.awarding_date,
				certificate_no: form.certificate_no || null
			}
			if (isAdmin) payload.status = form.status
			await updateAward(currentRow.value.id, payload)
			ElMessage.success('保存成功')
		}
		showDialog.value = false
		await loadTable()
	} catch (e) {
		console.error(e)
		ElMessage.error(e?.response?.data?.message || e?.message || '提交失败')
	} finally {
		submitting.value = false
	}
}

const handleView = (row) => {
	currentRow.value = row
	showView.value = true
}

const handleEdit = async (row) => {
	if (!canEdit(row)) {
		ElMessage.warning('仅可编辑“待审核”的奖项，已通过/已驳回请联系管理员处理')
		return
	}
	currentRow.value = row
	isEdit.value = true
	Object.assign(form, {
		award_name: row.awardName,
		achievement_name: row.achievementName ?? row.achievement_name ?? '',
		category: row.category,
		level: row.level,
		grade: row.grade || '',
		awarding_org: row.awardingOrg,
		awarding_date: row.awardingDate,
		certificate_no: row.certificateNo ?? row.certificate_no ?? '',
		status: row.status || 'PENDING'
	})
	showDialog.value = true
}

const handleDelete = async (row) => {
	try {
		await ElMessageBox.confirm('确定删除该奖项吗？删除后不可恢复', '删除确认', { type: 'warning' })
		await deleteAward(row.id)
		ElMessage.success('删除成功')
		await loadTable()
	} catch (e) {
		if (e !== 'cancel') {
			ElMessage.error(e?.response?.data || e?.message || '删除失败')
		}
	}
}

// 导出数据
const exportData = async () => {
	const { exportData: exportUtil } = await import('@/utils/exportUtils')
	
	const filters = {}
	
	await exportUtil('awards', filters, '获奖情况列表.xlsx')
}

loadTable()
</script>

<style scoped>
.awards { }
.page-header { margin-bottom: 16px; }
.page-title { margin: 0; font-size: 20px; }
.page-subtitle { margin: 4px 0 0 0; color: #666; }
.upload-demo { width: 100%; }
</style>